<template>
  <div class="container">
    <img :src="img" alt="" ref="img">
    <div class="tabbel">
        <div class="left" @click="$emit('close')">取消</div>
        <div class="right" @click="colums">完成</div>
    </div>
  </div>
</template>

<script>
import { updatePhoto } from '@/api/user'
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
export default {
  data () {
    return {
      cropper: null
    }
  },
  props: {
    img: {
      type: [String, Object],
      required: true
    }
  },
  components: {},
  mounted () {
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1, // 只能在裁剪的图片范围内移动
      dragMode: 'move', // 画布和图片都可以移动
      aspectRatio: 1, // 裁剪区默认正方形
      autoCropArea: 1, // 自动调整裁剪图片
      cropBoxMovable: false, // 禁止裁剪区移动
      cropBoxResizable: false, // 禁止裁剪区缩放
      background: false // 关闭默认背景
    })
  },
  computed: {},
  methods: {
    colums () { // 完成图片裁剪
      this.$toast.loading({
        message: '保存中...',
        forbidClick: true,
        loadingType: 'spinner',
        duration: 0
      })
      try {
        this.cropper.getCroppedCanvas().toBlob(async blob => {
        // 创建formDate数据
          const formData = new FormData()
          formData.append('photo', blob)
          const { data } = await updatePhoto(formData)
          console.log(data.data.photo)
          this.$emit('upPhoto', data.data.photo)
          this.$emit('close')
          console.log(data)
          this.$toast.success('更新成功')
        })
      } catch (err) {
        this.$toast.fail('更新失败')
      }
    }
  }
}
</script>

<style lang='less' scoped>
.container{
    height: 100%;
    background-color: black;
    img{
        width: 100%;
    }
    .tabbel{
        padding: 20px;
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        color: white;
        font-size: 30px;
        display: flex;
        justify-content: space-between;
    }
}
</style>
